package com.liuxing.javaSpringBoot.modules.account.dao;

import com.liuxing.javaSpringBoot.modules.account.entity.Resource;
import com.liuxing.javaSpringBoot.modules.common.entity.SearchBean;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * @File ResourceDao.java
 * @Auth liuxing
 * @Date 2021/8/23 17:45
 * @Email liuxing997@foxmail.com
 */
@Mapper
@Repository
public interface ResourceDao {

    //插入资源信息
    @Insert("insert into account_resource (create_date,permit)" +
            "values(#{createDate},#{permit})")
    @Options(useGeneratedKeys = true, keyColumn = "id", keyProperty = "id")
    void insertResource(Resource resource);

    //根据资源ID修改资源信息
    @Update("update account_resource set permit = #{permit}" +
            "where id = #{id}")
    void updateResourceById(Resource resource);

    //根据资源ID删除资源信息
    @Delete("delete from account_resource where id = #{id}")
    void deleteResourceByResourceId(int id);

    //根据资源ID查询资源信息
    @Select("select * from account_resource where id= #{id}")
    @Results(id="resourceResult", value={
            @Result(column="id", property="id"),
            @Result(column="id",property="roles",
                    javaType=List.class,
                    many=@Many(select="com.liuxing.javaSpringBoot.modules.account.dao.RoleDao.getRolesByResourceId"))
    })
    Resource getResourceByResourceId(int id);

    //根据角色ID查询资源信息
    @Select("select * from account_resource ar left join account_role_resource arr on ar.id = arr.resource_id "
            + "where arr.role_id = #{roleId}")
    List<Resource> getResourcesByRoleId(int roleId);

    //查询所有资源信息
    @Select("select * from account_resource")
    List<Resource> getAllResource();

    //批量插入资源信息
    @Insert("<script>"
            + "insert into account_resource (create_date,permit)" +
            " values <foreach collection='resources' item='resource' index='index' separator=','>"
            + "(#{resource.createDate},#{resource.permit})</foreach>"
            + "</script>")
    @Options(useGeneratedKeys = true,keyColumn = "id",keyProperty = "id")
    void insertResources(@Param("resources") List<Resource> resources);

    //分页查询资源信息
    @Select("<script>"
            + "select * from account_resource "
            + "<where> "
            + "<if test='keyword != \"\" and keyword != null'>"
            + " and (permit like '%${keyword}%' "
            + "</if>"
            + "</where>"
            + "<choose>"
            + "<when test='orderBy != \"\" and orderBy != null'>"
            + " order by ${orderBy} ${direction}"
            + "</when>"
            + "<otherwise>"
            + " order by id desc"
            + "</otherwise>"
            + "</choose>"
            + "</script>")
    List<Resource> getResourcesBySearchBean(SearchBean searchBean);
}
